<template>
  <div class="bg course-container">

    <!-- 查询区域 -->
    <div>
      <el-input style="width: 200px" clearable prefix-icon="el-icon-c-scale-to-original"
                @keyup.enter.native="load(1)" placeholder="查询预约内容" v-model="content"></el-input>
      <el-input style="width: 200px; margin: 0 5px" clearable prefix-icon="el-icon-user"
                @keyup.enter.native="load(1)" placeholder="查询发起人" v-model="username"></el-input>
      <el-button type="primary" style="margin: 0 5px" @click="load(1)">查询</el-button>
      <el-button type="info" style="margin: 0 5px" @click="reset">重置</el-button>
      <el-select style="margin: 0 5px" v-model="state" placeholder="筛选预约状态">
        <el-option label="待审核" value="待审核"></el-option>
        <el-option label="已通过" value="已通过"></el-option>
        <el-option label="已完成" value="已完成"></el-option>
        <el-option label="已拒绝" value="已拒绝"></el-option>
        <el-option label="已取消" value="已取消"></el-option>
      </el-select>
    </div>

    <!-- 增删区域 -->
    <div style="margin: 10px 0; height: 35px">
      <el-button type="info" plain v-if="user.role === '管理员'"
                 @click="exportData">批量导出</el-button>
    </div>

    <!-- 数据表格区域 -->
    <el-table :data="tableData" stripe class="datatable"
              :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="content" label="预约内容" sortable></el-table-column>
      <el-table-column prop="description" label="详情" show-overflow-tooltip></el-table-column>
      <el-table-column prop="username" label="发起人" sortable></el-table-column>
      <el-table-column prop="createTime" label="发起时间" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.createTime">{{ formatDate(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="reserveTime" label="预约时间" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.reserveTime">{{ formatDate(scope.row.reserveTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
      <el-table-column prop="state" label="状态" sortable></el-table-column>
      <el-table-column prop="handler" label="处理人" sortable></el-table-column>
      <el-table-column prop="handlerTime" label="处理时间" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.handlerTime">{{ formatDate(scope.row.handlerTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template v-slot="scope">
          <el-button size="mini" type="primary" plain
                     v-if="scope.row.state === '待审核'"
                     @click="approve(scope.row.id, scope.row.username);">通过</el-button>
          <el-button size="mini" type="danger" plain
                     v-if="scope.row.state === '待审核'"
                     @click="pass(scope.row.id, scope.row.username)">拒绝</el-button>
          <el-button size="mini" type="success" plain
                     v-if="scope.row.state === '已通过'"
                     @click="finish(scope.row.id, scope.row.username);">完成</el-button>
          <el-button size="mini" type="primary" plain
                     v-if="scope.row.state === '已完成' || scope.row.state === '已拒绝' || scope.row.state === '已通过'"
                     @click="handleEdit(scope.row)">添加备注</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器区域 -->
    <div style="margin: 10px 0">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[100, 200, 300, 400]"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>

    <!-- 步骤条 -->
    <div style="position: relative; top: 15px;">
      <el-steps :active="3" align-center>
        <el-step title="发布课程信息" icon="el-icon-c-scale-to-original" description="请核实相关课程信息"></el-step>
        <el-step title="学员预约课程" icon="el-icon-c-scale-to-original" description="学员根据需求预约课程"></el-step>
        <el-step title="审核处理" icon="el-icon-circle-check" description="处理人负责指导该学员和管理车辆，如需添加备注请单独一行添加，不得修改学员备注！"></el-step>
        <el-step title="完成预约" icon="el-icon-circle-check" description="在完成相关内容后即视为完成"></el-step>
        <el-step title=学员评价 icon="el-icon-document" description="学员可为相关教练和课程进行评价"></el-step>
      </el-steps>
    </div>

    <!-- 添加备注对话框 -->
    <el-dialog title="备注信息" :visible.sync="fromVisible" width="30%">
      <el-form :model="form" label-width="80px" style="padding-right: 20px" :rules="rules" ref="formRef">
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" @keyup.enter.native="save()"
                    placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="fromVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>


<script>
export default {
  name: "Course_check",

  data() {
    return {
      user: JSON.parse(localStorage.getItem('honey-user') || '{}'), // 从本地存储获取用户信息
      tableData: [],  // 存储所有的课程预约数据
      pageNum: 1,   // 当前页码
      pageSize: 5,  // 每页显示的数据条数
      form: {},  // 存储表单数据
      content: '',  // 查询的预约内容
      state: '',  // 查询的预约状态
      fromVisible: false,  // 控制备注弹窗的显示与隐藏
      username: '',  // 查询的发起人用户名
      rules: {  // 表单验证规则
        remark: [
          {required: true, message: '请输入备注', trigger: 'blur'},
        ]
      },
      ids: []  // 存储选中的课程预约 ID 数组
    }
  },

  created() {
    this.load()  // 组件创建时加载数据
  },

  beforeDestroy() {
    this.unReadCountPerUser();  // 组件销毁前统计未读消息数量
    this.countStudent();  // 组件销毁前统计当前学生数量
  },

  methods: {
    countStudent() {
      this.$request.get('/reserve/countCurrentStudent');  // 获取当前学生数量
    },

    formatDate(date) {  // 格式化日期的方法
      const options = {year: 'numeric', month: 'long', day: 'numeric'};
      return new Date(date).toLocaleDateString('zh-CN', options);
    },

    handleSelectionChange(rows) {  // 处理表格行选中变化
      this.ids = rows.map(v => v.id);  // 获取选中行的 ID 并存储
    },

    reset() {  // 重置查询条件的方法
      this.content = ''
      this.username = ''
      this.state= ''
      this.load()  // 重新加载数据
    },

    finish(id, username) {  // 完成预约的方法
      // 弹出确认完成预约的提示框
      this.$confirm('您确认完成了这个预约吗？', '完成预约', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送更新预约状态为已完成的请求
        this.$request.put(`/reserve/handle/${id}`, {state: '已完成'}).then(res => {
          if (res.code === '200') {
            this.$message.success('预约已成功完成');
            this.load();
            if (username) {
              // 如果有用户名，则发送消息通知
              this.$request.post(`/message/add/`, {
                state: '已完成',
                content: "课程预约",
                username: username
              });
            }
          } else {
            this.$message.error(res.msg);
          }
        }).catch(() => {});
      }).catch(() => {});
    },

    pass(id, username) {  // 拒绝预约的方法
      // 发送更新预约状态为已拒绝的请求
      this.$request.put(`/reserve/handle/${id}`, {state: '已拒绝'}).then(res => {
        if (res.code === '200') {
          this.$message.success('预约已成功拒绝');
          this.load();
          if (username) {
            // 如果有用户名，则发送消息通知
            this.$request.post(`/message/add/`, {
              state: '已拒绝',
              content: "课程预约",
              username: username
            });
          }
        } else {
          this.$message.error(res.msg);
        }
      }).catch(() => {});
    },

    approve(id, username) {  // 通过预约的方法
      // 发送更新预约状态为已通过的请求
      this.$request.put(`/reserve/handle/${id}`, {state: '已通过'}).then(res => {
        if (res.code === '200') {
          this.$message.success('预约已成功通过');
          this.load();
          if (username) {
            // 如果有用户名，则发送消息通知
            this.$request.post(`/message/add/`, {
              state: '已通过',
              content: "课程预约",
              username: username
            });
          }
        } else {
          this.$message.error(res.msg);
        }
      }).catch(() => {});
    },

    unReadCountPerUser() {  // 统计未读消息数量的方法
      this.$request.get(`/message/unReadCountPerUser`);
    },
    exportData() {  // 批量导出 excel 的方法
      if (!this.ids.length) {  // 没有选择行时全部导出
        window.open('http://localhost:9090/reserve/export?content=' + this.content)
      } else {
        let idStr = this.ids.join(',')  // 有选择行时根据 ID 导出
        window.open('http://localhost:9090/reserve/export?ids=' + idStr);
      }
    },

    handleEdit(row) {  // 编辑数据的方法
      this.form = JSON.parse(JSON.stringify(row));  // 深拷贝数据
      this.fromVisible = true;  // 打开弹窗
    },

    save() {  // 保存数据的方法
      this.$refs.formRef.validate((valid) => {  // 表单验证
        if (valid) {
          // 发送更新请求
          this.$request.put('/reserve/update', this.form).then(res => {
            if (res.code === '200') {
              this.$message.success('更新成功');
              this.load(1);
              this.fromVisible = false;
            } else {
              this.$message.error(res.msg);  // 弹出错误信息
            }
          })
        }
      });
    },

    load(pageNum) {  // 加载数据的方法
      if (pageNum) this.pageNum = pageNum;
      // 发送请求获取分页数据
      this.$request.get('/reserve/selectByPage', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          content: this.content,
          username: this.username,
          state: this.state,
          type: '课程',
          createTime: '',
          reserveTime: '',
          remark: '',
        }
      }).then(res => {
        this.tableData = res.data.records;
        this.total = res.data.total;
      })
    },

    handleCurrentChange(pageNum) {  // 处理分页变化的方法
      this.load(pageNum);
    },

  }
}
</script>


<style scoped>
.course-container {
  background: url('@/assets/bg/course.png') center/cover no-repeat;
}
</style>